$(function () {
    $('#memberTable').DataTable({
        "scrollX": true,
        'paging': true,
        'lengthChange': false,
        'pageLength': 20,
        'searching': true,
        'ordering': true,
        // "aaSorting":[[-2,"desc"]],//指定哪一列什么顺序排列
        'info': true,
        'autoWidth': false,
        'stripeClasses': ['row-white', 'row-gray'],
        "deferRender": true,
        "columnDefs": [{
            "targets": -1,
            "orderable": false
        }],
        // "fnDrawCallback": function (settings) {
        //     setTimeout(function () {
        //         $.fn.dataTable.tables({
        //             visible: true,
        //             api: true
        //         }).columns.adjust();
        //     }, 200);
        // },
        // "infoCallback": function(settings, start, end, max, total, pre) {},
        // 'createdRow': function(row, data, dataIndex) {

        // },
        "language": {
            //"info": "当前第_PAGE_页，共 _PAGES_页",
            "sInfo": "当前显示第 _START_ 到第 _END_ 条，共 _TOTAL_ 条",
            "sInfoFiltered": "(从_MAX_条筛选 )",
            "sInfoEmpty": "共筛选到0条",
            "sSearch": "搜索:",
            "sLengthMenu": "每页显示 _MENU_ 条",
            "sZeroRecords": "未筛选到相关内容",
            "paginate": {
                "sFirst": "首页", //首页和尾页必须在pagingType设为full_numbers时才可以
                "sLast": "尾页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "first": "First page",
                "last": "Last page",
                "next": "Next page",
                "previous": "Previous page"
            }
        }
    });
    var htmlTemp = "<div class='row'>";
    htmlTemp += "<div class='col-md-3'>";
    htmlTemp +=
        "<button id='add_device' type='button' class='btn btn-block btn-default' data-toggle='modal' data-target='#modal-default'>增加</button>";
    htmlTemp += "</div><div class='col-md-3'>";
    htmlTemp += "<button id='update' type='button' class='btn btn-block btn-default' data-toggle='modal' data-target='#modal-default' disabled >修改</button>";
    htmlTemp += "</div><div class='col-md-3'>";
    htmlTemp += "<button id='delete_devices' type='button' class='btn btn-block btn-default' disabled>删除</button>";
    htmlTemp += "</div></div>";
    $(".dataTables_filter").parent().parents().children().first()
        .append(htmlTemp);

    observer_dialog();
    observer_table();

    $("#update").click(function () {
        change_title('update');
        let target = $(".cb:checked");
        let devices_data = target.parents('td').siblings("td:not(:first,:last)");
        $.each(devices_data, function (i, item) {
            let target_id = $(this).attr('target');
            let edit_target = $('#' + target_id);
            if (i === 0) {
                edit_target.attr('disabled', 'disabled');
            }
            edit_target.val($(this).text());
        });
    });

    $("#add_device").click(function () {
        change_title('add');
    });

    $("#delete_devices").click(function () {
        let target = $(".cb:checked");
        let delete_target = [];
        $.each(target, function (i, item) {
            let item_target = $(this).parents('td').siblings("td:eq(1)").text();
            delete_target.push(item_target);
        });

        let request = {
            'catalog': $("#div_add").attr('cat'),
            'targets': delete_target
        };
        post('/data/deleteDevices/', request, function (msg) {
            //提示信息
            if (msg.code === 200) {
                //成功！延迟后刷新。
                console.log('delete success');
                window.parent.alertThis('success', '删除设备成功！');
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            } else {
                //失败，不刷新
                console.log('failed');
                window.parent.alertThis('danger', '删除失败！');
            }
        })

    });
});

$("tbody>tr>td").click(function (e) {
    let target = $(this).parent().find(':last');
    let is_checked = target.is(':checked');
    target.prop('checked', !is_checked);
    if (!is_checked) {
        $(this).css('font-weight', 'bold');
        $(this).siblings().css('font-weight', 'bold');
    } else {
        $(this).css('font-weight', 'normal');
        $(this).siblings().css('font-weight', 'normal');
    }
    check_button();
});

$("input[type='checkbox'][id!=select_all]").click(function (e) {
    // e.stopPropagation();
    let target = $(this);
    let is_checked = target.is(':checked');
    target.prop('checked', !is_checked);
    if (!is_checked) {
        $(this).css('font-weight', 'bold');
        $(this).siblings().css('font-weight', 'bold');
    } else {
        $(this).css('font-weight', 'normal');
        $(this).siblings().css('font-weight', 'normal');
    }
    check_button();
});


$("#select_all").change(function () {
    let is_checked = $("#select_all").is(":checked");
    $.each($(".cb"), function (index, val) {
        $(val).prop('checked', is_checked);
        if (is_checked) {
            $(this).parents('td').siblings().css('font-weight', 'bold');
        } else {
            $(this).parents('td').siblings().css('font-weight', 'normal');
        }
    });
    $(this).prop('checked', is_checked);
    check_button();
});

function check_button() {
    let select_length = $(".cb:checked").length;

    if (select_length === 1) {
        $('#update').removeAttr('disabled');
    } else {
        $('#update').attr('disabled', true);
    }

    if (select_length === 0) {
        $("#delete_devices").attr('disabled', true);
    } else {
        $("#delete_devices").removeAttr('disabled');
    }
}

function error_hint(selector, text) {
    if (text) {
        selector.parent().addClass("has-error");
        selector.parent().removeClass("has-success");
    } else {
        selector.parent().removeClass("has-error");
        selector.parent().addClass("has-success");
    }
    selector.prev().html(text);
}

$("#save").click(function () {
    let device_data = {};
    let is_full = true;
    $('.data').each(function (index, item) {
        let val = $(this).val();
        if (val) {
            device_data[$(this).attr('id')] = $(this).attr('id') !== 'model_name' ? parseFloat(val) : val;
        } else {
            $(this).focus();
            error_hint($(this), '请输入设备信息');
            is_full = false;
            return false;
        }
    });
    if (is_full) {
        let cat = $("#div_add").attr('cat');
        device_data['is_default'] = $("#is_default").val();
        let data = {
            'catalog': cat,
            'devices': device_data
        };

        let to_which_url = $(this).attr('to');
        let target_url = '';
        if (to_which_url === 'add') {
            target_url = '/data/addDevices/';
        } else if (to_which_url === 'update') {
            target_url = '/data/updateDevices/';
        } else {
            return false;
        }
        post(target_url, data, function (msg) {
            if (msg.code === 200) {
                $("#modal-default").modal('hide');
                window.parent.alertThis('success', target_url === 'add' ? '添加设备成功！' : '更新设备成功！');
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            } else {
                window.parent.alertThis('danger', msg.msg);
            }
        });
    }

});


$(".data").on('blur', function () {
    if ($(this).val()) {
        error_hint($(this), '');
    } else {
        error_hint($(this), '请输入参数值');
    }
});

function reset_add_form() {
    let target = $("#div_add>div>input");
    $.each(target, function (i, item) {
        if (i === 0) {
            $(this).removeAttr('disabled')
        }
        $(this).val('');//清除自己的内容
        $(this).parent().removeClass('has-success');//删除父类提示的样式
        $(this).parent().removeClass('has-error');//删除父类提示的样式
        $(this).prev().html('');//清空兄弟选择器中的提示
    });
}

//利用观察者模式进行处理有关对话框隐藏时重置数据的行为
function observer_dialog() {
    //选择一个需要观察的节点
    let targetNode = document.getElementById('modal-default');

    // 设置observer的配置选项
    let config = {attributes: true, subtree: true};

    // 当节点发生变化时的需要执行的函数
    let callback = function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                console.log('A child node has been added or removed.');
            } else if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                // console.log(mutation.target.classList.value);
                // console.log(mutation.target.classList.value.indexOf("in"));
                if (mutation.target.classList.value.indexOf("in") >= 0) {
                    //Dialog显示，不作处理
                } else {
                    //Dialog隐藏，重置表格
                    reset_add_form();
                }
            }
        }
    };
    // 创建一个observer示例与回调函数相关联
    let observer = new MutationObserver(callback);
    //使用配置文件对目标节点进行观测
    observer.observe(targetNode, config);
}


//利用观察者模式进行处理有关对话框隐藏时重置数据的行为
function observer_table() {
    //选择一个需要观察的节点
    let targetNode = document.getElementById('memberTable');

    // 设置observer的配置选项
    let config = {childList: true, subtree: true};

    // 当节点发生变化时的需要执行的函数
    let callback = function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            let is_checked = $("#select_all").is(":checked");
            $.each($(".cb"), function (index, val) {
                $(val).prop('checked', is_checked);
            });
            $(this).prop('checked', is_checked);
            check_button();
        }
    };
    // 创建一个observer示例与回调函数相关联
    let observer = new MutationObserver(callback);
    //使用配置文件对目标节点进行观测
    observer.observe(targetNode, config);
}

function change_title(type) {
    if (type === 'add') {
        let title = $("#dialog_title");
        let before_title = title.html();
        title.html("新增" + before_title.substring(2));
        $("#save").attr('to', 'add');
    } else if (type === 'update') {
        let title = $("#dialog_title");
        let before_title = title.html();
        title.html("修改" + before_title.substring(2));
        $("#save").attr('to', 'update');
    }
}
